import copy
import cv2 as cv
import numpy as np
import urllib.request
from threading import Thread
import queue
import time


_EXIT = False
im_q = queue.Queue(10)



def put_img_to_queue(im):
    if im_q.full():
        print('image queue is full ...')
    else:
        im_q.put(im)


def get_img_from_url(url):
    global _EXIT
    while True:
        try:
            imgSrc = urllib.request.urlopen(url)
        except:
            continue
        imgNp = np.array(bytearray(imgSrc.read()), dtype=np.uint8)
        img = cv.imdecode(imgNp, -1)
        put_img_to_queue(img)
        # if im_q.full():
        #     break
        

def get_img_from_queue():
    cv.namedWindow('d', 0)
    while True:
        if im_q.qsize() < 5:
            print('image queue is too short ... %d' % im_q.qsize())
            continue
        else:
            try:
                im = im_q.get()
            except:
                print('get image error ...')
                continue
            print('queue size is %d' % im_q.qsize())
            cv.imshow('d', im)
            if cv.waitKey(5) > 0:
                cv.destroyAllWindows()
                break


if __name__ == '__main__':
    url = 'http://192.168.0.104/cam-hi.jpg'
    # get_img_from_url(url)
    th1 = Thread(target=get_img_from_url, args=(url, ))
    th2 = Thread(target=get_img_from_queue, )
    th2.start()
    th1.start()
    th2.join()
    th1.join()













